/**
 * 
 * @version $Id: index.js 75 2013-11-08 09:24:04Z rainyjune@live.cn $
 */

window.YuanMap = {};

if ( ! window.console ) console = { log: function(){} };

var mapObj = null;

$(function(){
    $.getScript("http://webapi.amap.com/maps?v=1.2&key=97b27bfcd3d40ec66b150c4acb673034&callback=initMap");
});

function initMap() {
    var position = new AMap.LngLat(116.404,39.915);
    mapObj = new AMap.Map("mapContainer", { 
        center: position,
        resizeEnable: true,
        level: 13
    });
    
    // Load AMap plugins
    mapObj.plugin(["AMap.ToolBar", "AMap.OverView", "AMap.Scale", "AMap.Autocomplete"], function() {
        var tool = new AMap.ToolBar({
            direction: true,
            ruler:true,
            autoPosition: false
        });
        mapObj.addControl(tool);
        
        var view = new AMap.OverView();
        mapObj.addControl(view);
        
        var scale = new AMap.Scale();
        mapObj.addControl(scale);
        
        bindAutoCompleteEvent();
    });

    mapObj.plugin(["AMap.MapType"], function () {
        var mapType = new AMap.MapType({
            defaultType: 1
        });
        mapObj.addControl(mapType);
        
        $.getScript('javascript/base/AMap.Hotspot.js').then(function () {
            var hotspotObj = new AMap.Hotspot(mapObj, mapType);
            setTimeout(function () {
                hotspotObj.destroy();
            }, 10000);
        }, function () {
            debugger;
        });

        //console.log('mapType', mapType);

        //setTimeout(function () {
        //    //mapType = null;
        //    console.log('f');
        //    if (mapType.sublayers) {
        //        mapType.sublayers.road.layer.setMap(null);
        //        mapType.sublayers.traffic.layer.setMap(null);
        //    }
        //    var mapTypeNew = new AMap.MapType({
        //        defaultType: 1,
        //        showTraffic: true,
        //        showRoad: false
        //    });
        //    mapObj.addControl(mapTypeNew);
        //},5000);

        //setTimeout(function () {

        //    var mapTypeNew = new AMap.MapType({
        //        defaultType: 1,
        //        showRoad: true,
        //        showTraffic: false
        //    });
        //    mapType = mapTypeNew;
        //    mapObj.addControl(mapType);
        //},5000);
    });
    
    bindToggleHandler();
    bindMapResizeHandler();
    bindFormHandler();
}

function bindFormHandler() {
    $("#searchForm").on("submit", function(evt) {
        evt.preventDefault();
        var keyword = $("#keyword").val();
        parseKeyword(keyword);
        return false;
    });
}

function parseKeyword(keyword) {
    if (!keyword) return;
    var roadPattern = /^([a-z\u4e00-\u9fff]+)(?:路|街)$/;
    var lnglatPattern = /^(\-?\d+(?:\.\d+)?),\s*(\-?\d+(?:\.\d+)?)$/;
    var busPattern = /^[\u4e00-\u9fff]*[\d]+路(公交车?)?$/;
    var subwayPattern = /^(?:地铁|城铁)([\d]+|[\u4e00-\u9fff]+)号线$/;
    var provincePattern = /^([\u4e00-\u9fff]+)(自治区|特别行政区|省|直辖市)$/;
    var cityPattern = /^[^集][\u4e00-\u9fff]+市$/;
    var districtPattern = /^[\u4e00-\u9fff]+区$/;
    var routePattern = /^(?:从|自)?([\u4e00-\u9fff\w\d\-\.]+)(?:到|至)([\u4e00-\u9fff\w\d\-\.]+)$/;
    
    if (provincePattern.test(keyword)) {
        searchByProvince(keyword);
    } else if (cityPattern.test(keyword)) {
        searchByCity(keyword);
    } else if (districtPattern.test(keyword)) {
        searchByDistrict(keyword);
    } else if (busPattern.test(keyword)) {
        searchByBusName(keyword);
    } else if (lnglatPattern.test(keyword)) {
        var matchArr = lnglatPattern.exec(keyword);
        var lng = matchArr[1], lat = matchArr[2];
        regeocode(new AMap.LngLat((lng, lat)));
    } else if (roadPattern.test(keyword)) {
        SearchByRoadName(keyword);
    } else if (routePattern.test(keyword)) {
        var matchArr = routePattern.exec(keyword);
        var from = matchArr[1], to = matchArr[2];
        routeSearch(from, to);
    } else {
        searchPOI(keyword);
    }
}

function bindAutoCompleteEvent() {
    $( "#keyword" ).autocomplete({
        source: function(request, response){
            var pluginOption = {
                city: ""
            };
            var pluginObj = new AMap.Autocomplete(pluginOption);
            AMap.event.addListener(pluginObj, 'complete', function(result) {
                var tipsResult = parseTips(result);
                response(tipsResult);
            });
            pluginObj.search(request.term);
        }
    });
    return;    
}

function parseTips(result) {
    var returnArr = [];
    if (result.count > 0) {
        $.each(result.tips, function(k, v) {
            returnArr.push({label: v.name +  ' ' + v.district + ' ' + v.adcode, value: v.name});
        });
    }
    return returnArr;
}

function bindMapResizeHandler() {
    AMap.event.addListener(mapObj, 'resize', function(evt){
        return false;
    });
}

function bindToggleHandler() {
    var toggleContainer = $("#sidebarToggle"), 
            sidebar = $("#sidebar"), 
            openToggle = $("#openToggle"), 
            closeToggle = $("#closeToggle");
    
    toggleContainer.on("click", function(event){
        var targetId = event.target.id;
        if (targetId === 'closeToggle') {
            $(this).attr('class', "sidebarToggleopen");
            sidebar.attr('class', "sidebarclose");
            closeToggle.hide();
            openToggle.show();
        } else {
            $(this).attr('class', "sidebarToggleclose");
            sidebar.attr('class', "sidebaropen");
            openToggle.hide();
            closeToggle.show();
        }
        return false;
    });
}